const axios = require('axios');
const MockAdapter = require('axios-mock-adapter');
const normalAxios = axios.create();
const mockAxios = axios.create();
import {jsonToTreeByRoot} from "../utils/tools";
import _config from "./config";
import reqTools from "../utils/reqTools";

// mock 数据
var mock = new MockAdapter(mockAxios);

mock.onGet('/getAllOffice').reply(() => {
  return new Promise(function(resolve, reject) {
    reqTools.get('/api/sysOffice').then(res => {
      for(let i=0;i<res.data.length;i++){
        res.data[i].value = res.data[i].id;
        res.data[i].label = res.data[i].name;
        res.data[i].key = res.data[i].id;
      }

      resolve([200,jsonToTreeByRoot({
        json:res.data,
        idKey: "id",
        pidKey: "parentId",
        childKey: "children",
        rootId:0,
        validate: row => {
          return true;
        }
      })]);
    }).catch((err) => {
      resolve([500, err ]);
    });
  });
});

mock.onGet('/getAllOfficeId').reply(() => {
  return new Promise(function(resolve, reject) {
    reqTools.get('/api/sysOffice/findsysofficeId').then(res => {
      resolve([200,res.data]);
    }).catch((err) => {
      resolve([500, err ]);
    });
  });
});

mock.onGet('/getAgentTypeByOfficeId').reply((config) => {
  return new Promise(function(resolve, reject) {
    reqTools.get('/api/sysOffice/findAgentTypeByOfficeId',config).then(res => {
      resolve([200,res]);
    }).catch((err) => {
      resolve([500, err ]);
    });
  });
});

mock.onGet('/findChildrenOfficeByPId').reply((config) => {
  return new Promise(function(resolve, reject) {
    reqTools.get('/api/sysOffice/findChildrenOfficeByPId',config).then(res => {
      resolve([200,res]);
    }).catch((err) => {
      resolve([500, err ]);
    });
  });
});

mock.onPost('/addOffice').reply((config) => {
  return new Promise(function(resolve, reject) {
    reqTools.post( '/api/sysOffice',config.data
    ).then((res) => {
      resolve([200, res]);
    }).catch((err) => {
      resolve([500, err ]);
    });
  });
});
mock.onDelete('/delOffice').reply((config) => {
  return new Promise(function(resolve, reject) {
    reqTools.delete('/api/sysOffice/'+config.id).then((res) => {
      resolve([200, res]);
    }).catch((err) => {
      resolve([500, err ]);
    });
  });
});
mock.onPut('/updateOffice').reply((config) => {
  return new Promise(function(resolve, reject) {
    reqTools.put( '/api/sysOffice', config.data, 
   ).then((res) => {
      resolve([200, res ]);
    }).catch((err) => {
      resolve([500, err ]);
    });
  });
});

//通过机构ID和类型查询机构下的子机构信息
mock.onGet('/office/findAllOfficeByType').reply((config) => {
  return new Promise(function(resolve, reject) {
    reqTools.get('/api/sysOffice/findSysOfficeByType',config).then(res => {
      resolve([200,res]);
    }).catch((err) => {
      resolve([500, err ]);
    });
  });
});

export default mockAxios;
